<?php
// +----------------------------------------------------------------------
// | 文件上传管理
// +----------------------------------------------------------------------
// | @link ( http://www.yurnero.net )
// +----------------------------------------------------------------------
// | @copyright
// +----------------------------------------------------------------------
// | @licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author Haijun Wu <nicholasinlove@126.com>
// +----------------------------------------------------------------------
// | $Id: UploadAction.class.php 116 2011-05-11 12:44:01Z nicholasinlove1986@gmail.com $
// +----------------------------------------------------------------------


class UploadAction extends BaseAction {

	public function index() {
		redirect(__APP__);
	}
	
	public function uploadFile() {
		$allow_max_size = @ini_get('upload_max_filesize'); // 单位为m
		$allow_max_size_b = return_bytes(@ini_get('upload_max_filesize')); // 单位为b
		$this->assign('action_link', array('href'=>__URL__.'/uploadManager/', 'text' => '文件管理'));
		$this->assign('ur_here','上传文件');
		$this->assign('allow_max_size', $allow_max_size);
		$this->assign('allow_max_size_b', $allow_max_size_b);
		$this->display();
	}

	//附件上传处理程序
	public function fileUpload() {	
		if(!empty($_FILES)) {
			$path = ROOT_PATH . UPLOAD_DIR;			
			import("@.ORG.UploadFile");			
			$upload = new UploadFile();				
			$upload->maxSize    = return_bytes(@ini_get('upload_max_filesize'));
			$upload->allowExts  = array('doc', 'pdf', 'rar', 'zip');	
			$upload->savePath   = $path;	
			if(!$upload->upload()) {			
				$this->error($upload->getErrorMsg());				
			} else {		
				$info =  $upload->getUploadFileInfo();				
				$filearr = array($info[0]["savename"],$info[0]["savepath"].$info[0]["savename"],0);		
						
				if (file_exists($path.'file_list.php')) {
					$arr = F('file_list','',$path);
					$arr = unserialize($arr);
					if (empty($arr)) {
						@unlink($path .'file_list.php');
						$neswarr[1] = $filearr;
						F('file_list',serialize($neswarr),$path);
					} else {
						array_push($arr,$filearr);
						F('file_list',serialize($arr),$path);
					}					
				} else {
				    $neswarr[1] = $filearr;
					F('file_list',serialize($neswarr),$path);
				}
				set_log('upload(File, Name: '.$info[0]["savename"].')');
			}									
			echo C('blog_domain').UPLOAD_DIR.$info[0]["savename"];  			
		} else {
			$this->error ('非法操作');
		}  
	}
	
	//文件管理
	public function uploadManager() {
		/* 检查目录权限 */
		$path = ROOT_PATH . UPLOAD_DIR;
		$mask = file_mode_info($path);
		if ($mask === false) {	
			$warning = sprintf('目录 %s 不存在,请手动创建', $path);
			$this->assign('warning', $warning);			
		} elseif ($mask != 15) {		
			$warning = sprintf('目录 %s 权限有以下问题：', $path) . '<br/>';
			if (($mask&1) < 1) {
				$warning .= '不可读' . '&nbsp;&nbsp;';
			}
			if (($mask&2) < 1) {
				$warning .= '不可写' . '&nbsp;&nbsp;';
			}
			if (($mask&4) < 1) {
				$warning .= '不可追加数据' . '&nbsp;&nbsp;';
			}
			if (($mask&8) < 1) {
				$warning .= '不能修改文件';
			}
			$this->assign('warning', $warning);			
		} else {
		
		    /* 获取文件列表 */
			$real_list = array();
			$folder = opendir($path);
			while ($file = readdir($folder)) {
				if ((strpos($file,'.doc') || strpos($file,'.pdf') || strpos($file,'.rar') || strpos($file,'.zip'))!== false) {
					$real_list[] = $file;
				}
			}
			natsort($real_list);
		}	
	
		for($i=0; $i<count($real_list); $i++) {
			if($real_list[$i] != "." && $real_list[$i] != "..") {
				$list[] = array('file_name'=>$real_list[$i],'add_time'=>strftime("%Y-%m-%d %X",filemtime($path.$real_list[$i])),'file_size'=>num_bitunit(filesize($path.$real_list[$i])));
			}
		}
		
		//文件标识和下载数次插入数组当中
		$arr = unserialize(F('file_list','',$path));
		foreach ($list as $k=>$v) {
			foreach ($arr as $ks=>$vs) {
				if ($v['file_name'] == $vs[0]) {
					 $list[$k]['fid'] = $ks;
					 $list[$k]['count'] = $vs[2];
				}
			}
		}
		//echo empty($arr);
		//dump($arr);
	
		$this->assign('action_link', array('href'=>__URL__.'/uploadFile/', 'text' => '上传文件'));
		$this->assign('ur_here','文件管理');
		$this->assign('list',$list);
		$this->display();
	}
	
	//删除文件
	public function delFile() {	
		$this->checkLimits();
		$path = ROOT_PATH . UPLOAD_DIR;
		$arr = F('file_list','',$path);
		$arr = unserialize($arr);
		if ($_REQUEST['act']) {	
			if (isset($_POST['chkvalue'])) {		
	            $count = 0;
				foreach ($_POST['chkvalue'] as $file) {
					@unlink($path . $file);
					foreach ($arr as $k=>$v) {
						if ($v[0] == $file) {
							unset($arr[$k]);
						}
					}	
					F('file_list',serialize($arr),$path);				
					$count++;
				}	
				set_log('drop(File, Count: '.$count.')');
				$this->assign('jumpUrl',__URL__.'/uploadManager/');
				$this->success ('删除成功' );
			}		
		} else {
			$this->error ('非法操作');
		}
	}

	//可以统计下载次数
	public function attachment() {
	
		$path = ROOT_PATH . UPLOAD_DIR;
		if($_REQUEST['fid']) {
			$arr = F('file_list','',$path);
			$arr = unserialize($arr);
			$fid = $_REQUEST['fid'];
			if (!$arr[$fid]) { 
				$this->error ('文件未找到');
			}
			$arr[$fid][2] += 1;
			F('file_list',serialize($arr),$path);
			
			import("ORG.Net.Http");
            Http::download($arr[$fid][1],$arr[$fid][0]);
			
		} else {
			$this->error ('非法操作');
		}	
	}
	
	//编辑器图片上传处理程序
	public function uploadImage() {
	
		import("@.ORG.UploadFile"); 
		$upload = new UploadFile(); 
		$filedate = date('Ym');
		$upload->maxSize  = return_bytes(@ini_get('upload_max_filesize')); 
		$upload->allowExts  = explode(',','jpg,gif,png,jpeg,bmp');  
		$upload->savePath =  ROOT_PATH . IMAGE_DIR . $filedate.'/'; 
		$upload->thumb = true;
        $upload->thumbPrefix   =  'm_,s_';
        $upload->thumbMaxWidth =  '120,60'; 
        $upload->thumbMaxHeight = '140,60';
		$upload->saveRule = uniqid; 

        if(!$upload->upload()) { 
			header('Content-type:text/html;charset=utf-8');
			echo json_encode(array('error' => 1, 'message' => $upload->getErrorMsg()));
        }else { 
            $uploadList = $upload->getUploadFileInfo(); 
			if (C('iswatermark')) {
				import("@.ORG.Image");
				Image::water($uploadList[0]['savepath'].$uploadList[0]['savename'],C('watermark'),C('watermark_alpha'),C('watermark_place'));
			}
			header('Content-type:text/html;charset=utf-8');
			echo json_encode(array('error' => 0, 'url' => $uploadList[0]['savepath'].$uploadList[0]['savename']));
        }	
	}
	
	//编辑器图片管理程序
	public function fileManager() {
		//根目录路径，可以指定绝对路径，比如 /var/www/attached/
		$root_path = ROOT_PATH . DATA_DIR . '/Imagedata/';
		//根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
		$root_url =  ROOT_PATH . DATA_DIR . '/Imagedata/';
		
		//图片扩展名
		$ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
		
		//根据path参数，设置各路径和URL
		if (empty($_GET['path'])) {
			$current_path = realpath($root_path) . '/';
			$current_url = $root_url;
			$current_dir_path = '';
			$moveup_dir_path = '';
		} else {
			$current_path = realpath($root_path) . '/' . $_GET['path'];
			$current_url = $root_url . $_GET['path'];
			$current_dir_path = $_GET['path'];
			$moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);
		}
		//排序形式，name or size or type
		global $order;
		$order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);
		
		//不允许使用..移动到上一级目录
		if (preg_match('/\.\./', $current_path)) {
			echo 'Access is not allowed.';
			exit;
		}
		//最后一个字符不是/
		if (!preg_match('/\/$/', $current_path)) {
			echo 'Parameter is not valid.';
			exit;
		}
		//目录不存在或不是目录
		if (!file_exists($current_path) || !is_dir($current_path)) {
			echo 'Directory does not exist.';
			exit;
		}
		
		//遍历目录取得文件信息
		$file_list = array();
		if ($handle = opendir($current_path)) {
			$i = 0;
			while (false !== ($filename = readdir($handle))) {
				if ($filename{0} == '.' || $filename{0} == '..' || $filename == 'index.htm' || $filename == 'index.html' || $filename == 'index.php') {
					continue;
				}
				$file = $current_path . $filename;
				if (is_dir($file)) {
					$file_list[$i]['is_dir'] = true; //是否文件夹
					$file_list[$i]['has_file'] = (count(scandir($file)) > 2); //文件夹是否包含文件
					$file_list[$i]['filesize'] = 0; //文件大小
					$file_list[$i]['is_photo'] = false; //是否图片
					$file_list[$i]['filetype'] = ''; //文件类别，用扩展名判断
				} else {
					$file_list[$i]['is_dir'] = false;
					$file_list[$i]['has_file'] = false;
					$file_list[$i]['filesize'] = filesize($file);
					$file_list[$i]['dir_path'] = '';
					$file_ext = strtolower(array_pop(explode('.', trim($file))));
					$file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
					$file_list[$i]['filetype'] = $file_ext;
				}
				$file_list[$i]['filename'] = $filename; //文件名，包含扩展名
				$file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); //文件最后修改时间
				$i++;
			}
			closedir($handle);
		}
		
		//排序
		function cmp_func($a, $b) {
			if ($a['is_dir'] && !$b['is_dir']) {
				return -1;
			} else if (!$a['is_dir'] && $b['is_dir']) {
				return 1;
			} else {
				if ($GLOBALS['order'] == 'size') {
					if ($a['filesize'] > $b['filesize']) {
						return 1;
					} else if ($a['filesize'] < $b['filesize']) {
						return -1;
					} else {
						return 0;
					}
				} else if ($GLOBALS['order'] == 'type') {
					return strcmp($a['filetype'], $b['filetype']);
				} else {
					return strcmp($a['filename'], $b['filename']);
				}
			}
		}
		usort($file_list, 'cmp_func');
		
		$result = array();
		//相对于根目录的上一级目录
		$result['moveup_dir_path'] = $moveup_dir_path;
		//相对于根目录的当前目录
		$result['current_dir_path'] = $current_dir_path;
		//当前目录的URL
		$result['current_url'] = $current_url;
		//文件数
		$result['total_count'] = count($file_list);
		//文件列表数组
		$result['file_list'] = $file_list;
		
		//输出JSON字符串
		header('Content-type: application/json; charset=UTF-8');
		echo json_encode($result);
	}
	
}

?>